package com.baizhi.realm;

import com.baizhi.dao.AdminDao;
import com.baizhi.entity.Admin;
import com.baizhi.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;
import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {
    /*** 授权的realm 包含认证数据和授权数据的获取 昨天的Realm不需要了 */

    @Autowired(required = false)
    private AdminDao adminDao;
    @Autowired(required = false)
    private AdminService adminService;
    @Autowired(required = false)
    private HttpSession session;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //.1.获取用户名
        String username= (String) principals.getPrimaryPrincipal();

        //2.通过用户名查找数据库
        Set<String> permissions = adminService.selectResource(username);
        Set<String> roles = adminService.selectRole(username);

        //3.封装info
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.获取token中的数据
        UsernamePasswordToken token1=(UsernamePasswordToken) token;
        String username = token1.getUsername();

        //2.根据用户名 查询数据库
        Admin admin = adminDao.selectByUserName(username);

        //3.查询结果不为null 封装info
        if(admin!=null){
            session.setAttribute("a",admin);
            return new SimpleAuthenticationInfo(admin.getUserName(),admin.getPassword(),this.getName());
        }



        return null;

    }
}
